<template>
  <div>
    <div
      id="processDefineContainer"
      class="vue-bpmn-diagram-container"
    />
  </div>
</template>

<script>
import Viewer from 'bpmn-js/lib/NavigatedViewer.js'
import { getProcessDefinitionXml,getProcessDefinitionKeyXml } from '@/api/bpmn/bpmn'
import formatDate from '@/utils/date';
const convert = require('xml-js')

const getAssigneeFormJson = (json, taskDefinitionKey) => {
  if (
    json.hasOwnProperty('name') &&
      json.name === 'bpmn:userTask' &&
      json.hasOwnProperty('attributes') &&
      json.attributes.id === taskDefinitionKey
  ) {
    if (json.attributes.hasOwnProperty('camunda:assignee')) {
      return json.attributes['camunda:assignee']
    } else {
      return ''
    }
  }
  let result = ''
  if (json.hasOwnProperty('elements')) {
    json.elements.forEach(element => {
      result += getAssigneeFormJson(element, taskDefinitionKey)
    })
  }
  return result
}

export default {
  name: 'Detail',
  props: {
    processObj: {
      type: Object,
      required: true
    },
    type: {
      type: String,
      required: 'approve'
    },
    formList: {
      type: Array,
      default:() => []
    }
  },
  data() {
    return {
      diagramAdvanced: false,
      infoAdvanced: false,
      viewer: null,

      modalAssigneeAddVisible: false,
      modalUserAddVisible: false,
      modalStationAddVisible: false,
      processInfos: [],
      selectTask: null,
      element: null,
      overlayId: null,
      xmlJson: null
    }
  },
  watch: {
    processInfos: function(newval, oldval) {
      const self = this
      const canvas = self.viewer.get('canvas')
      newval.forEach(item => {
        if (item.actType === 'parallelGateway') {
          canvas.addMarker(item.actId, 'complete')
          return
        }

        if (item.actInstState === 0) {
          canvas.addMarker(item.actId, 'todo')
        } else if (item.actInstState === 1) {
          canvas.addMarker(item.actId, 'over')
        } else if (item.actInstState === 2) {
          canvas.addMarker(item.actId, 'terminal')
        } else if (item.actInstState === 4) {
          canvas.addMarker(item.actId, 'complete')
        } else {
          canvas.addMarker(item.actId, 'other')
        }
      })
    },
    element(newVal, oldval) {
      const self = this
      const overlays = self.viewer.get('overlays')
      if (self.overlayId) {
        overlays.remove(self.overlayId)
        self.overlayId = null
      }

      if (newVal.type === 'bpmn:UserTask') {
        const items = self.processInfos.filter(item => {
          return item.actId === newVal.id
        })

        if (items.length > 0) {
          const item = items[items.length - 1]
          console.log('item:', item)
          item.startTime = item.START_TIME_ ? this.dateFormat(item.START_TIME_) : item.START_TIME_
          item.endTime = item.END_TIME_ ? this.dateFormat(item.END_TIME_) : item.END_TIME_
          self.overlayId = overlays.add(item.actId, 'note', {
            position: {
              bottom: 0,
              right: 0
            },
            html:
                '<div style="width: 300px;background-color: aliceblue;">\n' +
                '            <form class="el-form el-form--label-right" style="padding: 10px">\n' +
                '                <div class="el-form-item el-form-item--mini">\n' +
                '                    <label for="text_1590738241000_80535" class="el-form-item__label" style="width: 100px;">用户:</label>\n' +
                '                    <div class="el-form-item__content" style="margin-left: 100px;width: 200px">\n' +
                '                        <span >'+ `${item.name ? item.name : '-'}` +'</span>\n' +
                '                    </div>\n' +
                '                </div>\n' +
                '                <div class="el-form-item el-form-item--mini">\n' +
                '                    <label for="text_1590738242000_16423" class="el-form-item__label" style="width: 100px;">开始时间:</label>\n' +
                '                    <div class="el-form-item__content" style="margin-left: 100px;width: 200px">\n' +
                '                        <span >'+ `${item.startTime ? item.startTime : '-'}` + '</span>\n' +
                '                    </div>\n' +
                '                </div>\n' +
                '                <div class="el-form-item el-form-item--mini">\n' +
                '                    <label for="text_1590738243000_57345" class="el-form-item__label" style="width: 100px;">结束时间:</label>\n' +
                '                    <div class="el-form-item__content" style="margin-left: 100px;width: 200px">\n' +
                '                        <span >'+ `${item.endTime ? item.endTime : '-'}` + '</span>\n' +
                '                    </div>\n' +
                '                </div>\n' +
                '            </form>\n' +
                '        </div>\n'
          })
        }
      }
    }
  },
  created() {
    console.log('processObj:', this.processObj)
    this.initDiagram()
  },
  methods: {
    initDiagram() {
      const self = this
      if (this.type == 'create') {
        getProcessDefinitionKeyXml(self.processObj.bpmn_key).then(res => {
          self.xmlJson = JSON.parse(convert.xml2json(res.bpmn20Xml))
          document.getElementById('processDefineContainer').innerHTML = ''
          self.viewer = new Viewer({ container: '#processDefineContainer' })
          self.viewer.importXML(res.bpmn20Xml, err => {
            document
              .getElementsByClassName('bjs-container')[0]
              .removeChild(document.getElementsByClassName('bjs-powered-by')[0]) // 移除logo
            if (err) {
              this.$notify.error({
                title: '错误',
                message: '获取流程错误'
              })
              return
            }
            const canvas = self.viewer.get('canvas')
            canvas.zoom('fit-viewport')

            var eventBus = self.viewer.get('eventBus')
            var events = ['element.click']

            events.forEach(function(event) {
              eventBus.on(event, function(e) {
                self.element = e.element
              })
            })
            self.processInfos = self.formList
          })
        })
      } else {
        console.log('self.processObj.procDefID:', self.processObj.procDefID)
        getProcessDefinitionXml(self.processObj.procDefID).then(res => {
          self.xmlJson = JSON.parse(convert.xml2json(res.bpmn20Xml))
          document.getElementById('processDefineContainer').innerHTML = ''
          self.viewer = new Viewer({ container: '#processDefineContainer' })
          self.viewer.importXML(res.bpmn20Xml, err => {
            document
              .getElementsByClassName('bjs-container')[0]
              .removeChild(document.getElementsByClassName('bjs-powered-by')[0]) // 移除logo
            if (err) {
              this.$notify.error({
                title: '错误',
                message: '获取流程错误'
              })
              return
            }
            const canvas = self.viewer.get('canvas')
            canvas.zoom('fit-viewport')

            var eventBus = self.viewer.get('eventBus')
            var events = ['element.click']

            events.forEach(function(event) {
              eventBus.on(event, function(e) {
                self.element = e.element
              })
            })
            self.processInfos = self.formList
          })
        })
      }
    },
    dateFormat(date){
      return formatDate(new Date(date),'yyyy-MM-dd hh:mm:ss')
    },
  }
}
</script>

<style lang="less" scoped>
  .vue-bpmn-diagram-container {
    height: 550px;
    width: 100%;
  }
</style>
<style lang="less" >
  .diagram-note {
    width: 400px;
    background-color: white;
    -moz-box-shadow: 2px 2px 10px #909090;
    -webkit-box-shadow: 2px 2px 10px #909090;
    box-shadow: 2px 2px 10px #909090;

    .ant-form-item {
      margin-bottom: 0px !important;
    }

    .ant-row {
      height: 20px !important;
    }
    .ant-form-item-label {
      line-height: 20px !important;
    }

    .ant-form-item-control {
      line-height: 20px !important;
    }
  }

  .todo:not(.djs-connection) .djs-visual > :nth-child(1) {
    stroke: #b7eb8f !important; /* color elements as red */
    fill: #f6ffed !important; /* color elements as red */
    fill-opacity: 0.5 !important;
  }
  .todo:not(.djs-connection) .djs-visual > :nth-child(2) {
    fill: #52c41a !important; /* color elements as red */
  }
  .over:not(.djs-connection) .djs-visual > :nth-child(1) {
    stroke: #91d5ff !important; /* color elements as red */
    fill: #e6f7ff !important; /* color elements as red */
    fill-opacity: 0.5 !important;
  }
  .over:not(.djs-connection) .djs-visual > :nth-child(2) {
    fill: #1890ff !important; /* color elements as red */
  }

  .terminal:not(.djs-connection) .djs-visual > :nth-child(1) {
    stroke: #ffa39e !important; /* color elements as red */
    fill: #fff1f0 !important; /* color elements as red */
    fill-opacity: 0.5 !important;
  }
  .terminal:not(.djs-connection) .djs-visual > :nth-child(2) {
    fill: #f5222d !important; /* color elements as red */
  }

  .complete:not(.djs-connection) .djs-visual > :nth-child(1) {
    stroke: #87e8de !important; /* color elements as red */
    fill: #e6fffb !important; /* color elements as red */
    fill-opacity: 0.5 !important;
  }
  .complete:not(.djs-connection) .djs-visual > :nth-child(2) {
    fill: #13c2c2 !important; /* color elements as red */
  }
  .other:not(.djs-connection) .djs-visual > :nth-child(1) {
    stroke: #ffd591 !important; /* color elements as red */
    fill: #fff7e6 !important; /* color elements as red */
    fill-opacity: 0.5 !important;
  }
  .other:not(.djs-connection) .djs-visual > :nth-child(2) {
    fill: #fa8c16 !important; /* color elements as red */
  }
</style>
